/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.io.FileWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload extends Servlet0
{
    /**
     * 
     */
    private static final long serialVersionUID = -2866433472225417267L;

    private static final String path =
        "/home/joinus/android/development/Server/Source/files/";

    private PreparedStatement ps_mem, ps_pre, ps_new;

    private Map<String,String> map = null;

    String id = null;
    String msg = null;
    String file = null;

    protected void initStmt()
    {
        ps_mem = DBConn.stmt("select idProfile from JoinsCampaign where idProfile=? and idCampaign=?");
        ps_pre = DBConn.stmt("update Campaign set version=version+1 where idCampaign=?");
        ps_new = DBConn.stmt("insert into Attachment(idProfile,idCampaign,filename,size,description,mimetype,hash,version)"
            + " values(?::bigint,?::bigint,?,?,?,?,?,(select version from Campaign where idCampaign=?))");
    }

    private boolean isMember(String id, String idCampaign) throws Exception
    {
        ps_mem.clearParameters();
        ps_mem.setInt(1, Integer.parseInt(id));  // .setString(1, id);
        ps_mem.setInt(2, Integer.parseInt(idCampaign));  // .setString(2, idCampaign);
        ResultSet rs = ps_mem.executeQuery();
        boolean ret = rs.next();
        rs.close();
        return ret;
    }

    private String arg(String name) throws Exception
    {
        String ret = map.get(name);
        if (ret == null) throw new Exception("Missing arg: "+name);
        System.out.println(name+" "+ret);
        return ret;
    }

    @SuppressWarnings("unchecked")
	private void setThings() throws Exception
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (!isMultipart) throw new Exception("not a multipart request");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(req);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                if (name.equals("file")) file = item.getString();
                if (name.equals("id")) id = item.getString();
                if (name.equals("msg")) msg = item.getString();
            }
        }

        if (id == null || msg == null || file == null)
            throw new Exception("missing id, msg or file");
    }

    public String handle() throws Exception
    {
        setThings();

        map = Auth.decode(id, msg);
        String idCampaign = arg("idCampaign");

        if (!isMember(id, idCampaign)) throw new Exception("not a campaign member");

        String filename = arg("filename");
        long size = file.length();
        String description = arg("description");
        String mimetype = arg("mimetype");
        String hash = UUID.randomUUID().toString().replaceAll("-", "");

        ps_pre.clearParameters();
        ps_pre.setInt(1, Integer.parseInt(idCampaign));  // .setString(1, idCampaign);
        ps_pre.executeUpdate();

        ps_new.clearParameters();
        ps_new.setInt(1, Integer.parseInt(id));  // setString(1, id);
        ps_new.setInt(2, Integer.parseInt(idCampaign));  // .setString(2, idCampaign);
        ps_new.setString(3, filename);
        ps_new.setLong(4, size);
        ps_new.setString(5, description);
        ps_new.setString(6, mimetype);
        ps_new.setString(7, hash);
        ps_new.setInt(8, Integer.parseInt(idCampaign));  // .setString(8, idCampaign);
        ps_new.executeUpdate();

        FileWriter fw = new FileWriter(path+hash);
        fw.write(file);
        fw.flush();
        fw.close();

        System.out.println("hash "+hash);
        System.out.println();

        return hash;
    }
}
